<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/18
 * Time: 17:28
 */

namespace app\admin\middleware;


use app\admin\service\AuthService;
use app\admin\service\ManagerRoleService;
use app\admin\service\RoleAuthService;

class Auth
{
    public function handle($request, \Closure $next)
    {
        // 获取菜单列表，则不需要权限
        if ((request()->pathinfo() !== 'menu' || !(request()->pathinfo() === 'menu' && request()->isGet())) &&
            (request()->pathinfo() !== 'account' || !(request()->pathinfo() === 'account' && request()->isPost()))) {
            // 超管放行
            if ($request->userInfo->id === 1) {
                // 超管
                return $next($request);
            }
            // 通过manager_id获取role_id
            $role_id = (new ManagerRoleService())->getRoleIdByManagerId($request->userInfo->id);
            if (empty($role_id)) {
                // 没有配置角色
                return fail('无权访问');
            }
            // 通过role_id获取auth_id集合
            $auth_ids = (new RoleAuthService())->getAuthIdByRoleId($role_id);
            if (empty($auth_ids)) {
                return fail('无权访问');
            }
            // 通过auth_ids把权限path查出来
            $paths = (new AuthService())->getPathByAuthIds($auth_ids);
            // 校验请求的方法是否在paths里
            $path = request()->pathinfo();
            $path = substr($path, 0, strrpos($path, "/"));
            if (request()->isGet()) {
                $path .= '/index';
            } elseif (request()->isPost()) {
                $path .= '/save';
            } elseif (request()->isPut()) {
                $path .= '/update';
            } elseif (request()->isDelete()) {
                $path .= '/delete';
            }
            if (!in_array($path, $paths)) {
                return fail('无权访问');
            }
        }
        return $next($request);
    }
}